package org.xiaoyu.rpc.remoting.transport;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;
import org.xiaoyu.rpc.remoting.codec.Codec;
import org.xiaoyu.rpc.remoting.codec.PacketCodeC;
import org.xiaoyu.rpc.remoting.packet.Packet;

import java.util.List;

/**
 * Created By Have
 * 2021/7/28 21:39
 */
public class NettyCodecAdapter {
    private final ChannelHandler encoder = new InternalEncoder();
    private final ChannelHandler decoder = new InternalDecoder();
    private Codec codec;

    public NettyCodecAdapter(Codec codec) {
        this.codec = codec;
    }

    public ChannelHandler getEncoder() {
        return encoder;
    }

    public ChannelHandler getDecoder() {
        return decoder;
    }

    private class InternalEncoder extends MessageToByteEncoder<Packet> {
        @Override
        protected void encode(ChannelHandlerContext ctx, Packet msg, ByteBuf out) throws Exception {
            codec.encode(ctx.channel(), msg, out);
        }
    }

    private class InternalDecoder extends ByteToMessageDecoder {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            do {
                int saveReaderIndex = in.readerIndex();
                Object msg = codec.decode(ctx.channel(), in);
                if (msg == Codec.DecodeResult.NEED_MORE_INPUT) {
                    in.readerIndex(saveReaderIndex);
                    break;
                } else {
                    if (msg != null) {
                        out.add(msg);
                    }
                }
            } while (in.isReadable());
        }
    }
}
